package com.whty.ws_fengx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whty.ws_fengx.domain.User;
import com.whty.ws_fengx.domain.Userfriend;
import com.whty.ws_fengx.mapper.UserfriendMapper;
import com.whty.ws_fengx.service.UserService;
import com.whty.ws_fengx.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.whty.ws_fengx.constant.UserConstant.USER_LOGIN_STATUS;

/**
* @author admin
* @description 针对表【ws_user(用户表)】的数据库操作Service实现
* @createDate 2022-08-02 15:40:40
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Value("${FengX.passwordSalt}")
    private String SALT;

    private String invalidChar = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserfriendMapper userfriendMapper;

    /**
     * 用户注册
     *
     * @param userAccount       用户注册账号
     * @param userPassword      用户注册密码
     * @param checkPassword     再次输入的密码
     * @return                  用户是否注册成功
     */
    @Override
    public boolean userRegister(String userAccount, String userPassword, String checkPassword) {
        //判断账号密码是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return false;
        }
        //判断再次输入的密码是否相等
        if (!userPassword.equals(checkPassword)) {
            return false;
        }
        //正则表达式判断账号是否有非法字符
        if (!checkAccountValid(userAccount)){
            return false;
        }
        //查找数据库中是否有相同userAccount用户
        User one = getUserByAccount(userAccount);
        if (one != null) {
            return false;
        }
        //md5加密密码
        String encryptPassword = encryptedPassword(userPassword);
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserNickname(userAccount);
        int insert = userMapper.insert(user);
        return insert > 0;
    }

    /**
     * 用户登录
     *
     * @param userAccount   用户账号
     * @param userPassword  用户密码
     * @return              返回用户信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //检验账号密码是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        //账号是否合法
        if (!checkAccountValid(userAccount)){
            return null;
        }
        String encryptPassword = encryptedPassword(userPassword);
        User user = getUserByAccount(userAccount);
        if (user == null) {
            return null;
        }
        if (!user.getUserPassword().equals(encryptPassword)){
            return null;
        }
        request.getSession().setAttribute(USER_LOGIN_STATUS, user);
        return user;
    }

    /**
     * 根据用户账号查找是否存在用户
     *
     * @param userAccount 用户账号
     * @return 返回加密用户信息，不存在返回null
     */
    @Override
    public User getUserByAccount(String userAccount) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserAccount, userAccount);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        return user != null? user : null;
    }

    @Override
    public boolean addUserFriend(User friendUser, User myUser) {
        Userfriend userfriend = new Userfriend();
        userfriend.setFriendId(friendUser.getId());
        userfriend.setUserId(myUser.getId());
        userfriend.setFrdNickname(friendUser.getUserNickname());
        int insert = userfriendMapper.insert(userfriend);
        return insert > 0;
    }

    /**
     * 检验用户账户是否合法
     *
     * @param userAccount   用户账户
     * @return              合法返回true，不合法返回false
     */
    private boolean checkAccountValid(String userAccount){
        String regEx = invalidChar;
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(userAccount);
        if (m.find()) {
            return false;
        }
        return true;
    }

    /**
     * 加密用户密码
     *
     * @param userPassword  用户密码
     * @return              加密后的用户密码
     */
    private String encryptedPassword(String userPassword){
        return DigestUtils.md5DigestAsHex(userPassword.getBytes());
    }
}




